package com.djx.案例;

import com.djx.监听.ZKConnectionWatcher;
import lombok.Data;
import lombok.SneakyThrows;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;

import java.io.IOException;


public class DunWatcher implements Watcher {
    private final String myIP = "192.168.15.132:2181";

    ZooKeeper zooKeeper;

    //用于本地化存储配置信息

    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }


    @SneakyThrows
    public void process(WatchedEvent watchedEvent) {

        if (watchedEvent.getType() == Event.EventType.None) {
            if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
                System.out.println("连接成功！");

            } else if (watchedEvent.getState() == Event.KeeperState.Disconnected) {
                System.out.println("断开连接！");
            } else if (watchedEvent.getState() == Event.KeeperState.Expired) {
                System.out.println("会话超时！");
//                zooKeeper = new ZooKeeper(myIP, 10000, this);

            } else if (watchedEvent.getState() == Event.KeeperState.AuthFailed) {
                System.out.println("认证失败！");
            }
        } else if (watchedEvent.getType() == Event.EventType.NodeDataChanged) {
            System.out.println("监听到节点修改");
         q();
        }

    }

    public void c() {
        try {
            zooKeeper = new ZooKeeper(myIP, 10000, this);
            byte[] data = zooKeeper.getData("/config/username", true, null);
            this.username = new String(data);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }


    public void q() {
        try {

            byte[] data = zooKeeper.getData("/config/username", true, null);
            this.username = new String(data);
        }  catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }


    public DunWatcher() {
        c();
    }

    @Test
    public void b() {
        try {

            while (true) {
                Thread.sleep(2000);
                DunWatcher dunWatcher = new DunWatcher();
                String username = dunWatcher.getUsername();
                System.out.println(" username :::  " + username);

                System.out.println("********************************");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

